#include "SDL.h"
#include "SDL_image.h"
#include <string> 

#include "data.h"
#include "image.h"

SDL_Surface *loadImage( std::string filename ) 
{ 
	//The image that's loaded 
	SDL_Surface* loadedImage = NULL; 
	//The optimized image that will be used 
	SDL_Surface* optimizedImage = NULL; 
	//Load the image using SDL_image 
	loadedImage = IMG_Load( filename.c_str() ); 
	//If the image loaded 
	if( loadedImage != NULL ) 
	{ 
		//Create an optimized image 
		optimizedImage = SDL_DisplayFormat( loadedImage ); 
		//Free the old image 
		SDL_FreeSurface( loadedImage ); 
	} 
	//If the image was optimized just fine 
	if( optimizedImage != NULL ) 
	{ 
		//Map the color key 
		Uint32 colorkey = SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF ); 
		//Set all pixels of color R 0, G 0xFF, B 0xFF to be transparent 
		SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorkey ); 
	} 
	//Return the optimized image 
	return optimizedImage;
} 

void displayMap(int mapID, SDL_Surface* destination)
{
	//Make a temporary rectangle to hold the offsets 
	SDL_Rect offset;
	// draw background
	offset.x=0;
	offset.y=0;
	SDL_BlitSurface( background[ map[mapID].background ], NULL, destination, &offset ); 
	// draw terrain
	for (int i=0;i<map[mapID].height;i++)
	{
		for (int j=0;j<map[mapID].width;j++)
		{
			offset.x=j*(SQUARE_WIDTH);
			offset.y=i*(SQUARE_HEIGHT)+SQUARE_START;
			SDL_BlitSurface( terrain[ map[mapID].terrain[i*map[mapID].width+j] ], NULL, destination, &offset ); 
		}
	
	}
}

void displayChar(int square_x,int square_y,int characterClip,SDL_Surface* destination)
{
	SDL_Rect offset;
	offset.x=square_x*SQUARE_WIDTH;
	offset.y=square_y*SQUARE_HEIGHT;
	SDL_BlitSurface( character[0], &charClip[characterClip], destination, &offset  ); 
}
